package com.world.core.listener;

import com.world.core.ServiceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

public class SystemInitListener extends Thread implements ServletContextListener {
    private static final Logger logger = LoggerFactory.getLogger(SystemInitListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }


    @Override
    public void contextInitialized(ServletContextEvent conEve) {
        logger.info("ServiceManager start !");
        ServiceManager.setApplicationContext(WebApplicationContextUtils.getRequiredWebApplicationContext(conEve.getServletContext()));
        logger.info("ServiceManager end !");

        init(conEve.getServletContext());
    }

    public static void init(ServletContext servletContext) {
        logger.info("Get source branch and version from META-INF/MANIFEST.MF...");
        String appServerHome = servletContext.getRealPath("/");
        File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
        if (manifestFile.exists()) {
            Manifest mf = new Manifest();
            try {
                mf.read(new FileInputStream(manifestFile));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Attributes mainAttributes = mf.getMainAttributes();
            logger.info("Subversion-Version: " + mainAttributes.getValue("Subversion-Version"));
            logger.info("Build-Jdk: " + mainAttributes.getValue("Build-Jdk"));
            servletContext.setAttribute("_buildNumber", mainAttributes.getValue("Subversion-Version"));
        }
    }

}
